import * as localforage from 'localforage';
import * as storage from '@/utils/storage';
import * as tools from '@/utils/util';

localforage.config({
    driver: localforage.WEBSQL,
    name: 'cache',
    version: 1.0,
    size: 4294967296,
    storeName: 'keyvaluepairs',
    description: 'some description'
});

/**
 * @function JS Sleep休眠函数
 * @param {*} time 
 */
export const sleep = async(time = 1000) => {
    return new Promise((resolve) => setTimeout(resolve, time));
}

export const queryAuthorRank = async(page = 0, size = 10, storage, tools) => {
    try {
        //查询URL
        var authors = await storage.getStoreDB(`system_blog_author_rank_${page}_${size}`);
        if (tools.isNull(authors)) {
            var queryURL = `${window.requestAPIConfig.restapi}/api/v_author_info?_p=${page}&_size=${size}&_sort=-blogs`;
            var res = await superagent.get(queryURL).set('accept', 'json');
            res.body.each((item) => {
                item.avatar = `${window._CONFIG['uploadURL']}/${item.avatar}`;
            });
            storage.setStoreDB(`system_blog_author_rank_${page}_${size}`, JSON.stringify(res.body), 3600 * 24);
            return res.body;
        } else {
            console.log(`authors:` + JSON.stringify(authors));
            return authors;
        }
    } catch (error) {
        console.log(error);
    }
}

export const queryAuthorByID = async(id, storage, tools) => {
    try {
        //查询URL
        var authors = await storage.getStoreDB(`system_blog_author_${id}`);
        if (tools.isNull(authors)) {
            var queryURL = `${window.requestAPIConfig.restapi}/api/v_author_info?_where=(username,eq,${id})`;
            var res = await superagent.get(queryURL).set('accept', 'json');
            res.body.each((item) => {
                item.avatar = `${window._CONFIG['uploadURL']}/${item.avatar}`;
            });
            if (tools.isNull(res.body)) {
                res.body = [{}];
            }
            storage.setStoreDB(`system_blog_author_${id}`, JSON.stringify(res.body), 3600 * 24);
            return res.body;
        } else {
            console.log(`authors:` + JSON.stringify(authors));
            return authors;
        }
    } catch (error) {
        console.log(error);
    }
}

export const queryBlogByAuthor = async(page = 0, size = 50, username, type, storage, tools) => {
    try {
        //查询URL
        var authors = await storage.getStoreDB(`system_blog_by_author_${username}_${type}_${page}_${size}`);
        if (tools.isNull(authors)) {
            var queryURL = `${window.requestAPIConfig.restapi}/api/bs_blog?_where=(create_by,eq,${username})&_p=${page}&_size=${size}&_sort=-${type}`;
            var res = await superagent.get(queryURL).set('accept', 'json');
            var result = res.body;

            //遍历并格式化日期
            result = window.__.filter(result, function(item) {
                //格式化日期
                var ctime = window.tools.formatDate(item['create_time'], 'yyyy-MM-dd');
                var time = window.tools.formatDate(item['create_time'], 'yyyyMMddhhmmss');
                item['createtime'] = window.tools.formatDate(
                    item['create_time'],
                    'yyyy-MM-dd hh:mm:ss'
                );
                item['create_time'] = ctime;
                item['timestamp'] = time;
                item['description'] = window.tools.abbreviation(
                    window.tools.delHtmlTag(item['content']),
                    300
                );
                item['title'] = window.tools.abbreviation(
                    window.tools.delHtmlTag(item['blog_title']),
                    100
                );

                //返回结果
                return true;
            });

            //根据ID编号去掉重复的数据
            result = window.__.uniq(result, false, 'id');

            storage.setStoreDB(`system_blog_by_author_${username}_${type}_${page}_${size}`, JSON.stringify(res.body), 3600 * 24);
            return res.body;
        } else {
            console.log(`authors:` + JSON.stringify(authors));
            return authors;
        }
    } catch (error) {
        console.log(error);
    }
}

/**
 * @function 查询数据
 * @param {*} tableName
 * @param {*} id
 */
export const queryTableDataByWhere = async(tableName, whereSQL, storage, tools, expiretime = 3600) => {

    //大写转小写
    tableName = tableName.toLowerCase();

    //更新URL PATCH	/api/tableName/:id	Updates row element by primary key
    var queryURL = `${window.requestAPIConfig.restapi}/api/${tableName}?${whereSQL}`;

    try {
        //获取缓存中的数据
        var cache = await storage.getStoreDB(`sys_query_table_cache@${tableName}&where@${whereSQL}`);

        //返回缓存值
        if (typeof cache != 'undefined' && cache != null && cache != '') {
            return cache;
        }

        var res = await superagent.get(queryURL).set('accept', 'json');

        if (res.body != null && res.body.length > 0) {
            storage.setStoreDB(`sys_query_table_cache@${tableName}&where@${whereSQL}`, res.body[0], expiretime);
        }

        return res.body[0];
    } catch (err) {
        console.log(err);
    }

}

/**
 * @function 查询数据
 * @param {*} tableName
 * @param {*} id
 */
export const queryTableDataByWhereMore = async(tableName, whereSQL, storage, tools, expiretime = 3600) => {

    //大写转小写
    tableName = tableName.toLowerCase();

    //更新URL PATCH	/api/tableName/:id	Updates row element by primary key
    var queryURL = `${window.requestAPIConfig.restapi}/api/${tableName}?${whereSQL}`;

    try {
        //获取缓存中的数据
        var cache = await storage.getStoreDB(`sys_user_watch_more_cache@${tableName}&where@${whereSQL}`);

        //返回缓存值
        if (typeof cache != 'undefined' && cache != null && cache != '') {
            return cache;
        }

        var res = await superagent.get(queryURL).set('accept', 'json');

        if (res.body != null && res.body.length > 0) {
            storage.setStoreDB(`sys_user_watch_more_cache@${tableName}&where@${whereSQL}`, res.body, expiretime);
        }

        return res.body;
    } catch (err) {
        console.log(err);
    }
}

/**
 * @function 查询所有用户信息
 */
export const queryAuthorsAll = async(page = 0, size = 99, type = 'exp', times = 101, storage, tools, expiretime = 3600) => {
    //设置用户数组
    var userList = []

    //从缓存中获取用户信息，如果没有获取到，则从数据库中查询

    //遍历查询最近1000条用户信息
    for (; page < times; page++) {

        let authorList = await queryTableDataByWhereMore('v_author_info', `_p=${page}&_size=${size}&_sort=-${type}`, storage, tools, expiretime);

        if (!authorList.length == 0) {
            userList.push(...authorList);
        }

        if (authorList.length == 0 || authorList.length < size) {
            break;
        }
    }

    //设置缓存，缓存一个周

    return userList;
}

/**
 * @function 查询所有用户信息
 */
export const queryAvatarAll = async(page = 0, size = 99, type = 'username', times = 101, storage, tools, expiretime = 3600 * 24 * 1.5) => {
    //设置用户数组
    var userList = []

    //从缓存中获取用户信息，如果没有获取到，则从数据库中查询

    //遍历查询最近1000条用户信息
    for (; page < times; page++) {

        let ulist = await queryTableDataByWhereMore('v_avatar', `_p=${page}&_size=${size}&_sort=-${type}`, storage, tools, expiretime);

        if (!ulist.length == 0) {
            userList.push(...ulist);
        }

        if (ulist.length == 0 || ulist.length < size) {
            break;
        }
    }

    //设置缓存，缓存一个周

    return userList;
}

/**
 * @function 查询所有用户信息
 */
export const queryWatchsAll = async(page = 0, size = 99, type = 'watch', table = 'v_watch', username, times = 101, storage, tools, expiretime = 3600) => {

    //设置用户数组
    var userList = [];

    //从缓存中获取用户信息，如果没有获取到，则从数据库中查询

    //遍历查询最近1000条用户信息
    for (; page < times; page++) {

        let ulist = await queryTableDataByWhereMore(table, `_where=(username,eq,${username})~and(status,eq,valid)&_p=${page}&_size=${size}&_sort=-${type}`, storage, tools, expiretime);

        if (!ulist.length == 0) {
            userList.push(...ulist);
        }

        if (ulist.length == 0 || ulist.length < size) {
            break;
        }
    }

    //设置缓存，缓存一个周

    return userList;
}

/**
 * @function 查询所有用户信息
 */
export const queryAvatarByName = async(username = 'username', storage = storage, tools = tools, expiretime = 3600 * 24 * 1.5) => {
    //更新URL PATCH	/api/tableName/:id	Updates row element by primary key
    var queryURL = `${window.requestAPIConfig.restapi}/api/v_avatar?_where=(username,eq,${username})`;
    try {
        //先从缓存中获取数据，如果没有获取到数据则从数据库中查询
        const cache = await storage.getStoreDB(`cache_avatar_${username}`);
        //设置
        if (cache == null || typeof cache == 'undefined') {
            var res = await superagent.get(queryURL).set('accept', 'json');
            await storage.setStoreDB(`cache_avatar_${username}`, res.body[0], 3600 * 24 * 7);
            return res.body[0];
        }
        console.log(`user avatar : ${cache}`);
        return cache;
    } catch (err) {
        console.log(err);
    }
}

/**
 * @function 查询所有博文信息
 */
export const queryBlogsAllByAuthor = async(page = 0, size = 99, username, type = 'new', times = 10, storage, tools, cacheflag = true) => {
    //设置用户数组
    var userList = []

    //如果cacheflag为true, 从缓存中获取用户信息，如果没有获取到，则从数据库中查询

    //遍历查询最近1000条用户信息
    for (; page < times; page++) {

        let ulist = await queryBlogByAuthor(page, size, username, type, storage, tools);

        if (!ulist.length == 0) {
            userList.push(...ulist);
        }

        if (ulist.length == 0 || ulist.length < size) {
            break;
        }
    }

    //如果cacheflag为true, 设置缓存，缓存一天

    return userList;
}

/**
 * @function 关注当前博客作者
 */
export const handleWatchAuthor = async(createuser, username, that, storage, tools, hashtoken) => {

    that.spinning = true;

    var cuser = createuser; //this.userInfo.username;
    var date = dayjs().format('YYYY-MM-DD HH:mm:ss');

    //先sleep 100ms 
    await sleep(300);

    //检查用户信息，如果是本人，则无法关注
    if (username == cuser) {
        that.$message.warning('无法关注博主本人！');
        return;
    }

    //检测远程是否存在状态为delete的关注记录，如果存在，状态改了valid即可

    //先获取远程服务端，此关注记录的数据，然后根据ID，修改此记录的状态为delete，然后patch提交上去即可
    let id = await queryTableDataByWhere('bs_blog_attention', `_where=(create_user,eq,${createuser})~and(watch_user,eq,${username})&_fields=id`, storage, tools, 3600);

    //如果远程服务端，没有获取到关注记录
    if (id !== null && typeof id !== 'undefined' && typeof id.id !== 'undefined' && id.id !== null) {

        //设置待修改的node
        let node = {
            id: id.id,
            status: 'valid',
        }

        //添加一条关注记录
        let result = await window.patchTableData('bs_blog_attention', id.id, node);

        //提示关注用户成功
        that.$message.success('关注用户成功！');

        //设置返回结果
        return result;
    }

    //获取当前最大id,作为pid
    var pid = '';
    var pdata = '';

    that.nowWatchFlag = true;

    let node = {
        id: tools.queryUniqueID(32),
        create_user: cuser,
        create_time: date,
        watch_user: username,
        watch_status: true,
        timestamp: new Date().getTime(),
        hashkey: '',
        hashtoken: '',
        consume: '',
        status: 'valid',
        pid: pid,
        pdata: pdata
    }

    //计算矿值信息
    var hashinfo = await hashtoken.calcuHashTokenFast('', '', JSON.stringify(node));

    node.hashkey = hashinfo.key;
    node.hashtoken = hashinfo.hash;
    node.consume = hashinfo.consume;

    //添加一条关注记录
    let result = await window.postTableData('bs_blog_attention', node);

    //提示关注用户成功
    that.$message.success('关注用户成功！');

    return result;
}

/**
 * @function 关注当前博客作者
 */
export const handleClearWatch = async(createuser, username, that, storage, tools, hashtoken) => {

    that.spinning = true;

    var cuser = createuser; //this.userInfo.username;
    var date = dayjs().format('YYYY-MM-DD HH:mm:ss');

    //先sleep 300ms 
    await sleep(300);

    //先获取远程服务端，此关注记录的数据，然后根据ID，修改此记录的状态为delete，然后patch提交上去即可
    let id = await queryTableDataByWhere('bs_blog_attention', `_where=(create_user,eq,${createuser})~and(watch_user,eq,${username})&_fields=id`, storage, tools, 3600);

    //如果远程服务端，没有获取到关注记录
    if (id == null || typeof id.id == 'undefined' || id.id == null) {
        return false;
    }

    //设置待修改的node
    var node = {
        id: id.id,
        status: 'delete',
    }

    //添加一条关注记录
    var result = await window.patchTableData('bs_blog_attention', id.id, node);

    //提示关注用户成功
    that.$message.success('取消关注成功！');

    return result;
}

/**
 * @function 处理作者主页切换书签功能函数
 */
export const handleAuthorTabChange = async(key, type, storage, manageAPI) => {
    try {
        this[type] = key;
        storage.setStore(`system_title_key`, key);
    } catch (error) {
        console.log(error);
    }
    try {
        await window.articleLoadData(window.blogArticle, storage, manageAPI);
    } catch (error) {
        console.log(error);
    }
    try {
        var title = this.tabListNoTitle.find((item) => {
            return item.key == key;
        })
        await this.handleArticleStyle(key, title);
    } catch (error) {
        console.log(error);
    }
}

/**
 * @function 根据查询的博文类型，计算出相应字段
 * @param {*} type 
 */
export const queryBlogTypeValue = (type) => {
    //定义排序类型
    var stype = 'create_time';
    //定义如果类型为热门，则以访问次数排序，否则以创建时间排序
    if (type == 'hot') {
        //当前作者博文数据
        stype = 'visit_count';
    } else if (type == 'new') {
        //当前作者博文数据
        stype = 'create_time';
    }
    return stype;
}

/**
 * @function 处理博文预览功能
 */
export const handleIntoBlogView = async(item, tools, that) => {
    try {
        //标签
        var tags = tools.deNull(item.tags);
        //跳转到博文详情页面
        that.$router.push(`/blog/view?id=${item.id}&author=${item.create_by}&tags=${tags}`);
    } catch (error) {
        console.log("$router go to error :" + error);
    }
}

/**
 * @function 查询当前评论信息
 */
export const queryCurReplayList = async(id) => {

    //初始化
    window.tools = window.tools == null ? tools : window.tools;

    //提交URL
    var queryURL = `${window.requestAPIConfig.restapi}/api/bs_comments?_where=(main_key,eq,${id})&_sort=create_time`;

    //根据业务编号，查询业务数据
    var wflow = await storage.getStoreDB(`cache_bs_comments_id@${id}`);

    //先sleep 100ms 
    await sleep(100);

    //从缓存中获取到评论信息，则直接返回
    try {
        if (wflow !== null && typeof wflow !== 'undefined' && Object.prototype.toString.call(wflow) === '[object Array]') {
            console.log(wflow);
            return wflow;
        }
    } catch (error) {
        console.log(error);
    }

    try {
        var res = await superagent.get(queryURL).set('accept', 'json');
        console.log(res);

        //如果只有一条数据，则返回[]；如果有多条数据，则返回多个数据
        if (
            typeof res.body == 'undefined' ||
            res.body == null ||
            res.body == '' ||
            res.body.length == 0
        ) {
            wflow = [];
        } else if (res.body.length >= 1) {
            wflow = res.body;
        }

        try {
            //遍历数据，格式化日期
            for await (let item of wflow) {
                try {
                    item['create_time'] = window.tools.formatDate(item['create_time'], 'yyyy-MM-dd');
                    item['replay'] = JSON.parse(item['replay']);
                    item['avatar'] = `${window._CONFIG['uploadURL']}/` + (await queryAvatarByName(item.create_by, storage)).avatar;
                } catch (error) {
                    console.log(error);
                }
                //遍历二级评论
                for await (let subItem of item['replay']) {
                    try {
                        subItem['avatar'] = `${window._CONFIG['uploadURL']}/` + (await queryAvatarByName(subItem.create_by, storage)).avatar;
                    } catch (error) {
                        console.log(error);
                    }
                }
            }
        } catch (error) {
            console.log(error);
        }

        try {
            //设置缓存信息
            await storage.setStoreDB(`cache_bs_comments_id@${id}`, JSON.stringify(wflow), 3600);
        } catch (error) {
            console.log(error);
        }

    } catch (err) {
        console.log(err);
    }

    return wflow;
}